#include "ListEditialog.h"
#include "ui_ListEditialog.h"

#include "utils/const.h"

#include <QFile>
#include <QFileDialog>
#include <QDebug>

ListEditialog::ListEditialog(const QString &title, const QStringList &fileList, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ListEditialog)
{
    ui->setupUi(this);
    setWindowTitle(title);
    setWindowIcon(QIcon(utils::Icon::Edit));
    for (QString filePath : fileList) {
        if (!QFile(filePath).exists()) {
            continue;
        }
        ui->listWidget->addItem(filePath);
    }
}

ListEditialog::~ListEditialog()
{
    delete ui;
}

void ListEditialog::setFilter(const QString &filter)
{
    m_filter = filter;
}

QStringList ListEditialog::getFileList()
{
    QStringList fileList;
    int count = ui->listWidget->count();
    for (int i = 0; i < count; i++) {
        QString filePath = ui->listWidget->item(i)->text();
        if (!QFile(filePath).exists()) {
            continue;
        }
        fileList << filePath;
    }
    return fileList;
}

void ListEditialog::on_btnAddNew_clicked()
{
    QStringList fileList = QFileDialog::getOpenFileNames(this, windowTitle(), "", m_filter);
    for (QString filePath : fileList) {
        if (!QFile(filePath).exists()) {
            continue;
        }
        ui->listWidget->addItem(filePath);
    }
}

void ListEditialog::on_btnRemove_clicked()
{
    QItemSelectionModel *selectionModel = ui->listWidget->selectionModel();
    // 创建一个选择集，包含所有选中的行
    QItemSelection selected = selectionModel->selection();

    // 遍历所有选中的项，并删除
    for (QModelIndex index : selected.indexes()) {
        ui->listWidget->model()->removeRow(index.row(), index.parent());
    }

}

void ListEditialog::on_btnClear_clicked()
{
    ui->listWidget->clear();
}

void ListEditialog::on_btnOK_clicked()
{
    emit editDone(getFileList());
    this->accept();
}

void ListEditialog::on_btnCancel_clicked()
{
    this->reject();
}
